/*******************************************************************************
 * Copyright (c) 2009-2011 ETCORE Labs. All rights reserved. 
 * 
 * This software is the confidential and proprietary information of ETCORE Labs.
 * You shall not disclose such confidential information and shall use it
 * only in accordance with the terms of the license agreement you entered into
 * with ETCORE Labs. 
 * 
 * Support can be obtained from support forums at:  http://www.etcore.com/
 * /
 *******************************************************************************/
package etcore.webapp.grouptalk.bookmarks.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import etcore.webapp.grouptalk.common.action.AbstractAction;
import etcore.webapp.grouptalk.common.config.Config;
import etcore.webapp.grouptalk.common.config.Messages;
import etcore.webapp.grouptalk.common.config.PageConstants;
import etcore.webapp.grouptalk.common.object.Group;
import etcore.webapp.grouptalk.common.object.Message;
import etcore.webapp.grouptalk.common.object.Topic;
import etcore.webapp.grouptalk.common.service.GroupService;
import etcore.webapp.grouptalk.common.service.MessageService;
import etcore.webapp.grouptalk.common.service.TopicService;
import etcore.webapp.grouptalk.user.object.User;
import etcore.webapp.grouptalk.util.DateUtil;
import etcore.webapp.grouptalk.util.StringDisplay;
import etcore.webapp.grouptalk.util.Symbols;

/**
 * This action validates the request and executes the command of editing a
 * book mark,then set the corresponding attributes for output
 * 
 * @author ETCORE GroupTalk Developers
 * 
 */
public class EditBookmarkAction extends AbstractAction {

	private static final long serialVersionUID = -7129979037018114361L;
	// validate result
	public static final int ACCESS_ALLOWED = 0;
	public static final int ERROR = 1;
	public static final int NOT_LOGGED = 2;

	// parameter/attributes constants

	public static final String OPERA = "opera";
	public static final String MERGE = "merge";
	public static final String CHANGE_TIME = "changeTime";

	public static final String CHANGE_AUTHOR = "changeAuthor";
	// utility constants

	@Override
	public int validate(HttpServletRequest request, HttpServletResponse response) {

		boolean isAdmin = (Boolean) request.getAttribute(PageConstants.ISADMIN);
		boolean notLogged = (Boolean) request
				.getAttribute(PageConstants.NOTLOGGED);
		if (notLogged)
			return NOT_LOGGED;
		TopicService topicService = new TopicService();
		GroupService groupService = new GroupService();
		MessageService msgService = new MessageService();
		String gmid = request.getParameter(PageConstants.ID);
		HttpSession session = request.getSession(true);
		User user = (User) session.getAttribute(PageConstants.SESSIONUSER);

		Message msg = null;
		Topic topic = null;
		Group group = null;

		if (gmid != null) {
			msg = msgService.findById(new Integer(gmid));
			if (msg != null) {
				topic = topicService.findById(new Integer(msg.getTid()));
				if (topic != null) {
					group = groupService.findById(new Integer(topic.getGid()));
					if (group != null && group.getOpen() == 3) {
						if (isAdmin
								|| (msg != null && user != null && msg
										.getUserName().equals(
												user.getUserName()))) {
							request.setAttribute(PageConstants.MESSAGEDETAIL,
									msg);
							request.setAttribute(PageConstants.GROUP, group);
							request.setAttribute(PageConstants.TOPIC, topic);

							return ACCESS_ALLOWED;
						}

					}
				}
			}
		}

		return ERROR;

	}

	@Override
	public String getForward(HttpServletRequest request, int validationResult) {
		if (NOT_LOGGED == validationResult) {
			request.setAttribute("init", "login");
			return "/";
		}
		if (ERROR == validationResult)
			return PageConstants.ACTION_PATH_ERROR;
		return PageConstants.PAGE_PATH_EDITBOOKMARK;
	}

	@Override
	public String getRedirect(HttpServletRequest request, int validationResult) {
		// TODO Auto-generated method stub

		return null;
	}

	@Override
	public void execute(int validationResult, HttpServletRequest request,
			HttpServletResponse response) {
		if (ACCESS_ALLOWED == validationResult) {
			editMessage(request);
			getGroups(request);
			getTopics(request);
		}

		// TODO Auto-generated method stub

	}

	private void editMessage(HttpServletRequest request) {
		MessageService messageService = new MessageService();
		Message message = (Message) request
				.getAttribute(PageConstants.MESSAGEDETAIL);

		String name = request.getParameter(PageConstants.NAME);
		String opera = request.getParameter(OPERA);
		String tid = request.getParameter(PageConstants.TID);
		String tag = request.getParameter(PageConstants.TAG);
		String up = request.getParameter(PageConstants.UP);
		String source = request.getParameter(PageConstants.SOURCE);
		// String stime =
		// request.getParameter(PageConstants.PAGE_VARIABLE_STIME);

		if (opera != null && opera.equals(MERGE) && tid != null) {
			boolean isAdmin = (Boolean) request
					.getAttribute(PageConstants.ISADMIN);
			HttpSession session = request.getSession(true);
			User user = (User) session.getAttribute(PageConstants.SESSIONUSER);
			message.setTid(new Integer(tid));
			message.setUp(new Integer(up));
			if (isAdmin) {
				String changeTime = request.getParameter(CHANGE_TIME);
				String changeAuthor = request.getParameter(CHANGE_AUTHOR);
				message.setName(name);
				if (Messages.TRUE.equals(changeAuthor))
					message.setUserName(user.getUserName());
				if (Messages.TRUE.equals(changeTime))
					message.setAddtime(DateUtil.getTime(Config.getProperty(Config.HOURS_DIFFERENCE)));
			} else {
				message.setName(StringDisplay.secureOutput(name));

				message.setAddtime(DateUtil.getTime(Config.getProperty(Config.HOURS_DIFFERENCE)));
			}


			message.setSource(source);
			message.setTag(tag);
			// if (isAdmin)
			// message.setContent(content);
			// else
			// message.setContent(StringDisplay.secureOutput(content));
			message = (Message) messageService.merge(message);
			String msg = null;
			String lang = (String) session.getAttribute(Messages.LANG);
			if (lang != null && lang.equals(Messages.LANG_EN)) {
				msg = Messages.getELabel(Messages.MSG_SUCCESS);
			} else {
				msg = Messages.getLabel(Messages.MSG_SUCCESS);
			}
			request.setAttribute(PageConstants.MSG, msg);
		}
	}

	private void getGroups(HttpServletRequest request) {
		List<Group> groupList = null;
		int groupNum = 50;
		String groupNumStr = request.getParameter(PageConstants.GROUPNUM);
		if (groupNumStr != null && !Symbols.BLANK.equals(groupNumStr))
			groupNum = Integer.parseInt(groupNumStr);
		GroupService groupService = new GroupService();
		Group group = (Group) request.getAttribute(PageConstants.GROUP);
		if (group.getOpen() == 1) {
			request.setAttribute(PageConstants.PAGE,
					PageConstants.PAGE_NAME_NEWSVIEW);
		} else if (group.getOpen() == 2) {
			request.setAttribute(PageConstants.PAGE,
					PageConstants.PAGE_NAME_COMMUNITYVIEW);
		} else if (group.getOpen() == 3) {
			request.setAttribute(PageConstants.PAGE,
					PageConstants.PAGE_NAME_BOOKMARKSVIEW);
		} else {
			request.setAttribute(PageConstants.PAGE,
					PageConstants.PAGE_NAME_GROUPDETAIL);
		}

		HttpSession session = request.getSession(true);
		String lang = (String) session.getAttribute(Messages.LANG);
		if (Messages.LANG_EN.equals(lang)) {

			groupList = groupService.findBy2Properties(PageConstants.OPEN,
					group.getOpen(), Messages.LANG_EN, new Integer(1), 0,
					groupNum);
		} else {
			groupList = groupService.findBy2Properties(PageConstants.OPEN,
					group.getOpen(), Messages.LANG_LOCAL, new Integer(1), 0,
					groupNum);
		}
		request.setAttribute(PageConstants.GROUPS, groupList);
	}

	private void getTopics(HttpServletRequest request) {
		TopicService topicService = new TopicService();
		Group group = (Group) request.getAttribute(PageConstants.GROUP);
		List<Topic> topics = topicService.findByProperty(PageConstants.GID,
				new Integer(group.getId()));
		request.setAttribute(PageConstants.TOPICS, topics);
	}

	@Override
	public boolean isForward(int validationResult) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean enablePostLoad() {
		// TODO Auto-generated method stub
		return false;
	}

	/* (non-Javadoc)
	 * @see etcore.webapp.grouptalk.controller.action.AbstractAction#buildSelfContextAndAttributes(int, javax.servlet.http.HttpServletRequest)
	 */
	@Override
	public List<String> getNamespacesOfMessages(HttpServletRequest request) {
		// TODO Auto-generated method stub
		return null;
	}

}
